<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <div>
        <div style="margin-bottom: 5px; text-align: center;">
            <el-input placeholder="请输入用户账号" :prefix-icon="Search" style="width: 200px; margin-left: 5px;" v-model="name"
                @keyup.enter="loadPost()" />
            <el-input placeholder="请输入用户姓名" :prefix-icon="Search" style="width: 200px; margin-left: 5px;"
                v-model="username" @keyup.enter="loadPost()" />
            <el-input placeholder="请输入用户手机号" :prefix-icon="Search" style="width: 200px; margin-left: 5px;"
                v-model="telephone" @keyup.enter="loadPost()" />
            <el-input placeholder="请输入用户邮箱" :prefix-icon="Search" style="width: 200px; margin-left: 5px;"
                v-model="email" @keyup.enter="loadPost()" />
        </div>

        <div style="margin-bottom: 5px; text-align: center;">
            <el-select v-model="sex" placeholder="请选择用户性别" style="width: 200px; margin-left: 5px;">
                <el-option v-for="item in sexData" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>

            <el-select v-model="role" placeholder="请选择用户角色" style="width: 200px; margin-left: 5px;">
                <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>

            <el-select v-model="status" placeholder="请选择用户状态" style="width: 200px; margin-left: 5px;"
                v-if="hasAuth('user-search')">
                <el-option v-for="item in statusData" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>

            <el-button type="success" :icon="Search" circle style="margin-left: 5px;" @click="loadPost()"
                v-if="hasAuth('user-search')" />

            <el-button type="primary" :icon="Refresh" circle style="margin-left: 5px;" @click="resetParam()" />

            <el-button type="primary" :icon="Plus" circle style="margin-left: 5px;" @click="add()"
                v-if="hasAuth('user-save')" />

            <el-button type="danger" :icon="Delete" circle style="margin-left: 5px;" @click="delHandle(null)"
                v-if="hasAuth('user-delete')" :disabled="delBtnStatus" />
        </div>

        <el-table :data="tableData" ref="multipleTableRef" tooltip-effect="dark" border style="width: 100%;" stripe
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />

            <el-table-column prop="avatar" label="用户头像" width="100">
                <template #default="scope">
                    <el-avatar size="small" :src="scope.row.avatar" />
                </template>
            </el-table-column>

            <el-table-column prop="name" label="用户账号" width="120" />

            <el-table-column prop="username" label="用户姓名" width="120" />

            <el-table-column prop="password" label="用户密码" width="120" v-if="user.role == 0" />

            <el-table-column prop="sex" label="性别" width="70">
                <template #default="scope">
                    <el-tag v-if="scope.row.sex == 1" type="primary">男</el-tag>
                    <el-tag v-else type="danger">女</el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="telephone" label="电话号码" width="120" />

            <el-table-column prop="email" label="邮箱" width="120" />

            <el-table-column prop="age" label="年龄" width="70" />

            <el-table-column prop="role" label="角色" width="150" :formatter="formatRole" />

            <el-table-column prop="status" label="用户状态" width="150">
                <template #default="scope">
                    <el-switch :model-value="scope.row.status == 1" active-color="#13ce66" inactive-color="#ff4949"
                        active-text="正常" inactive-text="注销" @change="modStatus(scope.row.id)"
                        :disabled="!hasAuth('user-modStatus')" />
                </template>
            </el-table-column>

            <el-table-column prop="createTime" label="注册时间" width="200" :formatter="formatDate" />

            <el-table-column prop="updateTime" label="修改时间" width="200" :formatter="formatDate" />

            <el-table-column fixed="right" label="操作" width="250" prop="operate">
                <template #default="scope">
                    <div v-if="scope.row.role != 1">
                        <el-button type="primary" :icon="Edit" circle @click="mod(scope.row)" style="margin-left: 5px;"
                            v-if="hasAuth('user-update')" />

                        <el-button type="danger" :icon="Delete" circle style="margin-left: 5px;"
                            @click="delHandle(scope.row.id)" v-if="hasAuth('user-delete')" />

                        <el-button type="success" :icon="Refresh" circle style="margin-left: 5px;"
                            @click="repass(scope.row)" v-if="hasAuth('user-repass')" />

                        <el-button size="small" type="success" @click="roleHandle(scope.row.id)"
                            v-if="hasAuth('user-role')" style="margin-right: 20px">
                            <el-icon>
                                <Rank />
                            </el-icon>
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-sizes="[5, 20, 50, 100]" :page-size="pageSize" background
            layout="total, sizes, prev, pager, next, jumper" :total="total" />

        <el-dialog v-model="centerDialogVisible" title="用户增改表单" width="50%" center>
            <el-form ref="formRef" :model="form" label-width="150px" :rules="rules"
                style="width: 800px; margin: 10px auto;" enctype="multipart/form-data">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户账号" prop="name">
                            <el-input v-model="form.name" style="width: 200px;" />
                        </el-form-item>

                        <el-form-item label="用户姓名" prop="username">
                            <el-input v-model="form.username" style="width: 200px;" />
                        </el-form-item>

                        <el-form-item label="手机号码" prop="telephone">
                            <el-input v-model="form.telephone" style="width: 200px;" />
                        </el-form-item>

                        <el-form-item label="账号密码" prop="password">
                            <el-input type="password" v-model="form.password" style="width: 200px;" show-password />
                        </el-form-item>

                        <el-form-item label="用户邮箱" prop="email">
                            <el-input v-model="form.email" style="width: 200px;" />
                        </el-form-item>

                        <el-form-item label="用户年龄" prop="age">
                            <el-input-number v-model="form.age" style="width: 200px;" :min="18" :max="50" />
                        </el-form-item>

                        <el-form-item label="用户性别" prop="sex">
                            <el-select v-model="form.sex" style="width: 200px;">
                                <el-option v-for="item in sexData" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="用户头像" prop="avatar">
                            <el-upload action="#" list-type="picture-card" :auto-upload="false" accept="image/*"
                                :file-list="fileList" :limit="1" :on-change="submitUpload">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="用户角色" prop="role" v-if="form.update == 0">
                    <el-radio-group v-model="form.role" size="small">
                        <div v-for="item in roleData" :key="item.id" style="margin-top: 5px;">
                            <el-radio v-if="item.register == 1" :label="item.id" border>
                                {{ item.name }}
                            </el-radio>
                        </div>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button type="primary" @click="centerDialogVisible = false">取消</el-button>
                <el-button type="success" @click="save">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="roleDialogVisible" title="分配角色" width="600px">
            <el-radio-group v-model="form.role" size="small">
                <div v-for="item in roleData" :key="item.id" style="margin-top: 15px;">
                    <el-radio v-if="item.register == 1" :label="item.id" border>
                        {{ item.name }}
                    </el-radio>
                </div>
            </el-radio-group>

            <template #footer>
                <el-button @click="roleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="doMod()">确 定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
// eslint-disable-next-line vue/multi-word-component-names
import { ref, reactive, onMounted, computed } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'
import { Store } from '@/store/index'
import api from '@/axios/index'
import { 
  Search, 
  Refresh, 
  Plus, 
  Delete, 
  Edit, 
  Rank 
} from '@element-plus/icons-vue'
// 获取 store 实例
const store = Store()

// refs
const multipleTableRef = ref()
const formRef = ref()



// 数据响应式
const user = JSON.parse(localStorage.getItem("CurUser"))
const name = ref("")
const username = ref("")
const telephone = ref("")
const email = ref("")
const status = ref(1)
const role = ref("")
const roleData = ref([])
const sex = ref("")

const statusData = [
    { label: "正常", value: 1 },
    { label: "禁用", value: 0 }
]

const sexData = [
    { label: "女", value: 0 },
    { label: "男", value: 1 }
]

const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(5)
const tableData = ref([])
const roleDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const delBtnStatus = ref(true)
const multipleSelection = ref([])

// 表单数据
const form = reactive({
    avatar: "",
    name: "",
    username: "",
    password: "",
    telephone: "",
    email: "",
    age: 18,
    sex: 1,
    role: "",
    update: 0
})

const fileList = ref([])
const rules = {
    role: [
        { required: true, message: "请选择用户角色", trigger: 'blur' },
    ],
    name: [
        { required: true, message: "请输入用户账号", trigger: 'blur' },
        { min: 3, max: 20, message: "3-20个字符", trigger: 'blur' },
    ],
    username: [
        { required: true, message: "请输入用户姓名", trigger: 'blur' },
        { min: 2, max: 8, message: "2-8个字符", trigger: 'blur' },
    ],
    telephone: [
        { required: true, message: "请输入手机号码", trigger: 'blur' },
        { min: 11, max: 11, message: "请输入11位手机号", trigger: 'blur' },
        { pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(18[0-9])|166|198|199|(147))\d{8}$/, message: "手机号码不正确" }
    ],
    email: [
        { required: true, message: "请输入邮箱", trigger: 'blur' },
        { type: 'email', message: "邮箱格式不正确", trigger: 'blur' },
    ],
    sex: [{ required: true, message: "请选择用户性别", trigger: 'blur' }],
    age: [{ required: true, message: "请输入用户年龄", trigger: 'blur' }],
    avatar: [{ required: true, message: "请上传用户头像", trigger: 'blur' }],
    password: [
        { required: true, message: "请输密码", trigger: "blur" },
        { min: 6, max: 16, message: "6-16个字符", trigger: "blur" }
    ],
}

// 计算属性
const hasAuth = computed(() => {
    return function (perm) {
        return store.permList.includes(perm)
    }
})

// 方法
const roleHandle = (id) => {
    api.get("/user/info/" + id).then(res => {
        Object.assign(form, res.data)
    })
    roleDialogVisible.value = true
}

const resetParam = () => {
    name.value = ""
    username.value = ""
    telephone.value = ""
    email.value = ""
    sex.value = ""
    role.value = ""
    if (user.role == 0)
        status.value = ""
    else
        status.value = 1
}

const loadPost = () => {
    api.post("/user/listPage", {
        pageSize: pageSize.value,
        pageNum: pageNum.value,
        param: {
            name: name.value,
            username: username.value,
            telephone: telephone.value,
            email: email.value,
            sex: sex.value + '',
            status: status.value + '',
            role: role.value + ''
        }
    }).then((res) => {
        console.log(res)
        if (res.code == 200) {
            tableData.value = res.data
            if (res.length == 0 && pageNum.value != 1) {
                pageNum.value = 1
                loadPost()
            }
            total.value = res.total
        } else {
            ElMessage({
                message: '数据查询失败',
                type: "error"
            })
        }
    })
}

const handleSizeChange = (val) => {
    console.log(`每页 ${val} 条`)
    pageNum.value = 1
    pageSize.value = val
    loadPost()
}

const handleCurrentChange = (val) => {
    console.log(`当前页: ${val}`)
    pageNum.value = val
    loadPost()
}

const formatDate = (row, column) => {
    let data = row[column.property]
    if (data == null)
        return null

    let dt = new Date(data)
    return (dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate())
}

const add = () => {
    resetForm()
    centerDialogVisible.value = true
}

const resetForm = () => {
    Object.assign(form, {
        avatar: "",
        name: "",
        username: "",
        password: "",
        telephone: "",
        email: "",
        age: 18,
        sex: 1,
        role: "",
        update: 0
    })
    fileList.value = []
}

const submitUpload = (file) => {
    console.log(file)
    let formData = new FormData()
    formData.append("file", file.raw)
    formData.append("name", file.name)
    api.post("/file/upload", formData, {
        headers: { "Content-Type": "multipart/form-data" }
    }).then(res => {
        console.log(res)
        if (res.code === 200) {
            form.avatar = res.url
            ElMessage.success("图片上传成功")
        } else {
            ElMessage.error("图片上传失败")
        }
    })
}

const mod = (data) => {
    api.get("/user/info/" + data.id).then(res => {
        Object.assign(form, res.data)
        if (form.avatar != null) {
            fileList.value = []
            fileList.value.push({
                url: form.avatar
            })
        }
        form.update = 1
    })
    centerDialogVisible.value = true
}

const save = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (form.id) {
                doMod()
            } else {
                doSave()
            }
        } else {
            ElMessage.error('请填写正确的表单')
        }
    })
}

const doSave = () => {
    api.post("/user/save", form).then(res => {
        if (res.code == 200) {
            ElMessage({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                    resetForm()
                    loadPost()
                    centerDialogVisible.value = false
                }
            })
        } else {
            ElMessage({
                message: res.msg,
                type: "error",
            })
        }
    })
}

const doMod = () => {
    api.post("/user/update", form).then(res => {
        if (res.code == 200) {
            ElMessage({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                    resetForm()
                    loadPost()
                    centerDialogVisible.value = false
                    roleDialogVisible.value = false
                }
            })
        } else {
            ElMessage({
                message: res.msg,
                type: "error",
            })
        }
    })
}

const handleSelectionChange = (val) => {
    console.log(val)
    multipleSelection.value = val
    delBtnStatus.value = val.length == 0
}

const delHandle = (id) => {
    console.log(id)
    var ids = []
    if (id) {
        ids.push(id)
    } else {
        multipleSelection.value.forEach(row => {
            ids.push(row.id)
        })
    }
    console.log(ids)

    ElMessageBox.confirm('此操作将永久删除用户数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        api.post('/user/deleteBatch', ids, {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).then(res => {
            res = res.data
            if (res.code == 200) {
                ElMessage({
                    showClose: true,
                    message: '恭喜你，操作成功',
                    type: 'success',
                    onClose: () => {
                        loadPost()
                    }
                })
            } else {
                ElMessage.error(res.msg)
            }

        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

const modStatus = (id) => {
    api.post("/user/modStatus/" + id).then((res) => {
        if (res.code == 200) {
            ElMessage({
                message: "修改成功",
                type: "success",
                onClose: () => {
                    loadPost()
                },
            })
        } else {
            ElMessage({
                message: "操作失败！",
                type: "error",
            })
        }
    })
}

const repass = (row) => {
    ElMessageBox.confirm("确定要重置用户【" + row.username + "】的密码吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        api.post("/user/repass/" + row.id).then(() => {
            ElMessage({
                showClose: true,
                message: "恭喜你，操作成功",
                type: "success",
                onClose: () => {
                    loadPost()
                },
            })
        })
    }).catch(() => {
        ElMessage.error("取消成功")
    })
}

const loadRole = () => {
    api.post("/role/listPage", {
        pageSize: 1000,
        pageNum: 1,
        param: {
            status: 1 + '',
        }
    }).then((res) => {
        if (res.code == 200) {
            roleData.value = res.data
        } else {
            ElMessage({
                message: '数据查询失败',
                type: "error"
            })
        }
    })
}

const formatRole = (row) => {
    let temp = roleData.value.find((item) => {
        return item.id == row.role
    })
    return temp && temp.name
}

// 生命周期
onMounted(() => {
    loadRole()
    loadPost()
})
</script>

<style scoped>
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>